<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">日志管理</h2>
    </div>

    <!-- 统计卡片 -->
    <div class="grid kpi">
      <div class="card kpi slide-up" style="animation-delay: 0.1s">
        <div class="icon" style="background: var(--primary)">📊</div>
        <div class="meta">
          <div class="label">总日志数</div>
          <div class="value">{{ logStats.totalLogs }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.2s">
        <div class="icon" style="background: var(--success)">✅</div>
        <div class="meta">
          <div class="label">操作日志</div>
          <div class="value">{{ logStats.actionLogs }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.3s">
        <div class="icon" style="background: var(--danger)">❌</div>
        <div class="meta">
          <div class="label">错误日志</div>
          <div class="value">{{ logStats.errorLogs }}</div>
        </div>
      </div>
      <div class="card kpi slide-up" style="animation-delay: 0.4s">
        <div class="icon" style="background: var(--info)">🔐</div>
        <div class="meta">
          <div class="label">登录日志</div>
          <div class="value">{{ logStats.loginLogs }}</div>
        </div>
      </div>
    </div>

    <!-- 筛选器 -->
    <div class="card filters slide-up" style="animation-delay: 0.1s">
      <div class="filter-row">
        <div class="field">
          <label>日志类型</label>
          <select v-model="activeLogType" @change="handleLogTypeChange" class="input">
            <option value="action">行为日志</option>
            <option value="error">错误日志</option>
            <option value="login">登录日志</option>
          </select>
        </div>
        <div class="field">
          <label>开始时间</label>
          <DateField v-model="queryParams.startTime" mode="datetime" />
        </div>
        <div class="field">
          <label>结束时间</label>
          <DateField v-model="queryParams.endTime" mode="datetime" />
        </div>
        <div class="field">
          <label>搜索关键字</label>
          <input 
            type="text" 
            v-model="queryParams.key" 
            placeholder="搜索用户ID、操作内容等"
            class="input"
            @input="debouncedSearch"
          />
        </div>
        <div class="field">
          <button @click="resetFilters" class="btn secondary">重置</button>
        </div>
        <div class="field">
          <button @click="handleSearch" class="btn primary">
            <span class="icon">🔍</span>
            搜索
          </button>
        </div>
      </div>
    </div>



    <!-- 行为日志表格 -->
    <div v-if="activeLogType === 'action'" class="card table-container slide-up" style="animation-delay: 0.2s">
      <div class="table-header">
        <h3>行为日志</h3>
        <div class="table-actions">
          <button @click="refreshLogs" class="btn secondary">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="table">
          <thead>
            <tr>
              <th>用户ID</th>
              <th>操作类型</th>
              <th>操作动作</th>
              <th>API地址</th>
              <th>IP地址</th>
              <th>操作结果</th>
              <th>操作时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="loading-row">
              <td colspan="8" class="loading">
                <div class="spinner"></div>
                加载中...
              </td>
            </tr>
            <tr v-else-if="actionLogs.length === 0" class="empty-row">
              <td colspan="8" class="empty">暂无数据</td>
            </tr>
            <template v-else>
              <tr v-for="log in actionLogs" :key="`action-${log.id}`" class="data-row">
                <td class="log-user">{{ log.userId || '-' }}</td>
                <td>{{ log.type || '-' }}</td>
                <td class="log-action">{{ log.action || '-' }}</td>
                <td>{{ log.apiUrl || '-' }}</td>
                <td class="log-ip">{{ log.ip || '-' }}</td>
                <td>
                  <span :class="['badge', getResultColor(log.result)]">
                    {{ getResultText(log.result) }}
                  </span>
                </td>
                <td class="log-time">{{ formatLogTime(log.creationTime) }}</td>
                <td>
                  <button @click="viewLogDetail(log)" class="btn small secondary">
                    <span class="icon">👁️</span>
                    详情
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 错误日志表格 -->
    <div v-if="activeLogType === 'error'" class="card table-container slide-up" style="animation-delay: 0.2s">
      <div class="table-header">
        <h3>错误日志</h3>
        <div class="table-actions">
          <button @click="refreshLogs" class="btn secondary">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="table">
          <thead>
            <tr>
              <th>用户ID</th>
              <th>错误信息</th>
              <th>API地址</th>
              <th>IP地址</th>
              <th>发生时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="loading-row">
              <td colspan="6" class="loading">
                <div class="spinner"></div>
                加载中...
              </td>
            </tr>
            <tr v-else-if="errorLogs.length === 0" class="empty-row">
              <td colspan="6" class="empty">暂无数据</td>
            </tr>
            <template v-else>
              <tr v-for="log in errorLogs" :key="`error-${log.id}`" class="data-row">
                <td class="log-user">{{ log.userId || '-' }}</td>
                <td class="error-message">{{ log.message || '-' }}</td>
                <td>{{ log.api || '-' }}</td>
                <td class="log-ip">{{ log.ip || '-' }}</td>
                <td class="log-time">{{ formatLogTime(log.creationTime) }}</td>
                <td>
                  <button @click="viewLogDetail(log)" class="btn small secondary">
                    <span class="icon">👁️</span>
                    详情
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 登录日志表格 -->
    <div v-if="activeLogType === 'login'" class="card table-container slide-up" style="animation-delay: 0.2s">
      <div class="table-header">
        <h3>登录日志</h3>
        <div class="table-actions">
          <button @click="refreshLogs" class="btn secondary">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      
      <div class="table-wrapper">
        <table class="table">
          <thead>
            <tr>
              <th>账号</th>
              <th>用户ID</th>
              <th>登录结果</th>
              <th>IP地址</th>
              <th>登录类型</th>
              <th>说明</th>
              <th>登录时间</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="loading" class="loading-row">
              <td colspan="8" class="loading">
                <div class="spinner"></div>
                加载中...
              </td>
            </tr>
            <tr v-else-if="loginLogs.length === 0" class="empty-row">
              <td colspan="8" class="empty">暂无数据</td>
            </tr>
            <template v-else>
              <tr v-for="log in loginLogs" :key="`login-${log.id}`" class="data-row">
                <td class="log-user">{{ log.account || '-' }}</td>
                <td class="log-user">{{ log.userId || '-' }}</td>
                <td>
                  <span :class="['badge', getLoginResultColor(log.result)]">
                    {{ getLoginResultText(log.result) }}
                  </span>
                </td>
                <td class="log-ip">{{ log.ip || '-' }}</td>
                <td>{{ log.type || '-' }}</td>
                <td>{{ log.explain || '-' }}</td>
                <td class="log-time">{{ formatLogTime(log.creationTime) }}</td>
                <td>
                  <button @click="viewLogDetail(log)" class="btn small secondary">
                    <span class="icon">👁️</span>
                    详情
                  </button>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination slide-up" style="animation-delay: 0.3s">
      <div class="pagination-info">
        共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <button 
          @click="changePage(pagination.current - 1)" 
          :disabled="pagination.current <= 1"
          class="btn secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button 
            v-for="page in getPageNumbers()" 
            :key="page"
            @click="changePage(page)"
            :class="['btn', page === pagination.current ? 'primary' : 'secondary']"
          >
            {{ page }}
          </button>
        </span>
        <button 
          @click="changePage(pagination.current + 1)" 
          :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)"
          class="btn secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 日志详情弹窗 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetailModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>日志详情</h3>
          <button @click="closeDetailModal" class="btn close">✕</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedLog" class="log-detail">
            <div v-for="(value, key) in selectedLog" :key="key" class="detail-item">
              <label>{{ getFieldLabel(key) }}:</label>
              <div class="detail-value">{{ formatDetailValue(key, value) }}</div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeDetailModal" class="btn secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { 
  LogService, 
  type LogQueryRequest, 
  type ActionLog, 
  type ErrorLog, 
  type LoginLog,
  formatLogTime,
  getResultText,
  getResultColor,
  getLoginResultText,
  getLoginResultColor
} from '../services/log'
import DateField from '../components/DateField.vue'
import { useAuthStore } from '../stores/auth'

// 响应式数据
const activeLogType = ref<'action' | 'error' | 'login'>('action')
const loading = ref(false)
const showDetailModal = ref(false)
const selectedLog = ref<ActionLog | ErrorLog | LoginLog | null>(null)

// 查询参数
const queryParams = reactive<LogQueryRequest>({
  pageIndex: 1,
  pageSize: 20,
  startTime: '',
  endTime: '',
  key: ''
})

// 分页信息
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0
})

// 日志数据 - 使用Map进行缓存优化
const logCache = new Map<string, { data: any[], total: number, timestamp: number }>()
const CACHE_DURATION = 5 * 60 * 1000 // 5分钟缓存

// 日志数据
const actionLogs = ref<ActionLog[]>([])
const errorLogs = ref<ErrorLog[]>([])
const loginLogs = ref<LoginLog[]>([])

// 统计数据
const logStats = reactive({
  totalLogs: 0,
  actionLogs: 0,
  errorLogs: 0,
  loginLogs: 0
})

// 计算属性 - 当前显示的日志列表
const currentLogs = computed(() => {
  switch (activeLogType.value) {
    case 'action':
      return actionLogs.value
    case 'error':
      return errorLogs.value
    case 'login':
      return loginLogs.value
    default:
      return []
  }
})

// 防抖搜索
const debounce = (func: Function, delay: number) => {
  let timeoutId: ReturnType<typeof setTimeout>
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

const debouncedSearch = debounce(() => {
  // 搜索时重置到第一页
  pagination.current = 1
  searchLogs()
}, 500)

// 将显示值（YYYY-MM-DD HH:mm[:ss] 或 带T分隔）转为接口需要的 ISO 字符串
const formatLocalDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return ''
  const m = dateTimeStr.match(/^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?$/)
  if (m) {
    const [, y, mo, d, h, min, s] = m
    return `${y}-${mo}-${d}T${h}:${min}:${s || '00'}`
  }
  const date = new Date(dateTimeStr)
  if (!isNaN(date.getTime())) {
    const pad = (n: number) => String(n).padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
  }
  return dateTimeStr
}

// 初始化时间范围（默认最近7天）
const initTimeRange = () => {
  const now = new Date()
  const sevenDaysAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
  
  // 用于显示的中文格式 YYYY-MM-DD HH:mm:ss
  const formatDisplayDateTime = (date: Date) => {
    const pad = (n: number) => String(n).padStart(2, '0')
    const year = date.getFullYear()
    const month = pad(date.getMonth() + 1)
    const day = pad(date.getDate())
    const hours = pad(date.getHours())
    const minutes = pad(date.getMinutes())
    const seconds = pad(date.getSeconds())
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
  
  queryParams.endTime = formatDisplayDateTime(now)
  queryParams.startTime = formatDisplayDateTime(sevenDaysAgo)
}

// 生成缓存键
const getCacheKey = (logType: string, params: any) => {
  return `${logType}_${JSON.stringify(params)}`
}

// 检查缓存是否有效
const isCacheValid = (timestamp: number) => {
  return Date.now() - timestamp < CACHE_DURATION
}

// 切换日志类型
const handleLogTypeChange = () => {
  pagination.current = 1
  searchLogs()
}

// 处理搜索按钮点击
const handleSearch = () => {
  pagination.current = 1
  // 清除相关缓存
  clearRelatedCache()
  searchLogs()
}

// 重置筛选条件
const resetFilters = () => {
  queryParams.startTime = ''
  queryParams.endTime = ''
  queryParams.key = ''
  pagination.current = 1
  // 清除缓存并重新搜索
  clearRelatedCache()
  searchLogs()
}

// 清除相关缓存
const clearRelatedCache = () => {
  const keysToDelete: string[] = []
  logCache.forEach((_, key) => {
    if (key.startsWith(activeLogType.value)) {
      keysToDelete.push(key)
    }
  })
  keysToDelete.forEach(key => logCache.delete(key))
}

// 优化的搜索日志函数
const searchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      startTime: formatLocalDateTime(queryParams.startTime),
      endTime: formatLocalDateTime(queryParams.endTime),
      key: queryParams.key || ''
    }
    
    // 检查缓存
    const cacheKey = getCacheKey(activeLogType.value, params)
    const cached = logCache.get(cacheKey)
    
    if (cached && isCacheValid(cached.timestamp)) {
      // 使用缓存数据
      updateLogData(cached.data, cached.total)
      loading.value = false
      return
    }
    
    let response
    switch (activeLogType.value) {
      case 'action':
        response = await LogService.getActionLogs(params)
        break
      case 'error':
        response = await LogService.getErrorLogs(params)
        break
      case 'login':
        response = await LogService.getLoginLogs(params)
        break
    }
    
    if (response && response.code === 0 && response.data) {
      const data = response.data.data || []
      const total = response.data.total || 0
      
      // 缓存数据
      logCache.set(cacheKey, {
        data,
        total,
        timestamp: Date.now()
      })
      
      updateLogData(data, total)
    }
  } catch (error) {
    console.error('获取日志失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新日志数据的统一函数
const updateLogData = (data: any[], total: number) => {
  // 使用nextTick确保DOM更新的性能
  nextTick(() => {
    switch (activeLogType.value) {
      case 'action':
        actionLogs.value = data
        logStats.actionLogs = total
        break
      case 'error':
        errorLogs.value = data
        logStats.errorLogs = total
        break
      case 'login':
        loginLogs.value = data
        logStats.loginLogs = total
        break
    }
    pagination.total = total
    
    // 更新总日志数
    logStats.totalLogs = logStats.actionLogs + logStats.errorLogs + logStats.loginLogs
  })
}

// 刷新日志
const refreshLogs = () => {
  // 清除缓存强制刷新
  clearRelatedCache()
  searchLogs()
}

// 切换页码
const changePage = (page: number) => {
  if (page < 1 || page > Math.ceil(pagination.total / pagination.pageSize)) return
  pagination.current = page
  searchLogs()
}

// 优化的页码生成函数
const getPageNumbers = () => {
  const totalPages = Math.ceil(pagination.total / pagination.pageSize)
  const current = pagination.current
  const pages: number[] = []
  
  if (totalPages <= 7) {
    // 如果总页数小于等于7，显示所有页码
    for (let i = 1; i <= totalPages; i++) {
      pages.push(i)
    }
  } else {
    // 复杂分页逻辑
    if (current <= 4) {
      for (let i = 1; i <= 5; i++) {
        pages.push(i)
      }
      pages.push(-1) // 省略号
      pages.push(totalPages)
    } else if (current >= totalPages - 3) {
      pages.push(1)
      pages.push(-1) // 省略号
      for (let i = totalPages - 4; i <= totalPages; i++) {
        pages.push(i)
      }
    } else {
      pages.push(1)
      pages.push(-1) // 省略号
      for (let i = current - 1; i <= current + 1; i++) {
        pages.push(i)
      }
      pages.push(-1) // 省略号
      pages.push(totalPages)
    }
  }
  
  return pages
}

// 查看日志详情
const viewLogDetail = (log: ActionLog | ErrorLog | LoginLog) => {
  selectedLog.value = log
  showDetailModal.value = true
}

// 关闭详情弹窗
const closeDetailModal = () => {
  showDetailModal.value = false
  selectedLog.value = null
}

// 获取字段标签
const getFieldLabel = (key: string): string => {
  const labels: Record<string, string> = {
    id: 'ID',
    userId: '用户ID',
    type: '类型',
    action: '操作动作',
    version: '版本',
    apiUrl: 'API地址',
    ip: 'IP地址',
    params: '参数',
    result: '结果',
    resultMessage: '结果信息',
    creationTime: '创建时间',
    message: '错误信息',
    api: 'API',
    account: '账号',
    code: '代码',
    explain: '说明'
  }
  return labels[key] || key
}

// 格式化详情值
const formatDetailValue = (key: string, value: any): string => {
  if (value === null || value === undefined) return '-'
  
  if (key === 'creationTime') {
    return formatLogTime(value)
  }
  
  if (key === 'result') {
    if (activeLogType.value === 'login') {
      return getLoginResultText(value)
    } else {
      return getResultText(value)
    }
  }
  
  if (key === 'params' && typeof value === 'string') {
    try {
      return JSON.stringify(JSON.parse(value), null, 2)
    } catch {
      return value
    }
  }
  
  return String(value)
}

// 组件挂载时初始化
onMounted(() => {
  initTimeRange()
  searchLogs()
})
</script>

<style scoped>
/* 统计卡片样式 */
.grid.kpi {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-4, 16px);
  margin-bottom: var(--space-6, 24px);
}

.card.kpi {
  display: flex;
  align-items: center;
  gap: var(--space-3, 12px);
  padding: var(--space-4, 16px);
  background: var(--card-bg, #ffffff);
  border-radius: var(--radius, 8px);
  box-shadow: var(--shadow, 0 2px 8px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--border-light, #e5e7eb);
  transition: all 0.3s ease;
}

.card.kpi:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-lg, 0 4px 16px rgba(0, 0, 0, 0.15));
}

.card.kpi .icon {
  width: 48px;
  height: 48px;
  border-radius: var(--radius, 8px);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
  flex-shrink: 0;
}

.card.kpi .meta {
  flex: 1;
}

.card.kpi .label {
  font-size: var(--text-sm, 14px);
  color: var(--text-secondary, #6b7280);
  margin-bottom: var(--space-1, 4px);
  font-weight: 500;
}

.card.kpi .value {
  font-size: var(--text-2xl, 24px);
  font-weight: 700;
  color: var(--text, #111827);
  line-height: 1;
}

/* 表格样式 */
.table-container {
  background: var(--card-bg, #ffffff);
  border-radius: var(--radius, 8px);
  box-shadow: var(--shadow, 0 2px 8px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--border-light, #e5e7eb);
  overflow: hidden;
  margin-bottom: var(--space-6, 24px);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--space-4, 16px);
  border-bottom: 1px solid var(--border-light, #e5e7eb);
  background: var(--bg-secondary, #f9fafb);
}

.table-header h3 {
  margin: 0;
  font-size: var(--text-lg, 18px);
  font-weight: 600;
  color: var(--text, #111827);
}

.table-actions {
  display: flex;
  gap: var(--space-2, 8px);
}

.table-wrapper {
  overflow-x: auto;
  contain: layout style paint;
  will-change: scroll-position;
}

.table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--text-sm, 14px);
}

.table th,
.table td {
  padding: var(--space-3, 12px);
  text-align: left;
  border-bottom: 1px solid var(--border-light, #e5e7eb);
  vertical-align: middle;
}

.table th {
  font-weight: 600;
  color: var(--text-secondary, #6b7280);
  background: var(--bg-secondary, #f9fafb);
  position: sticky;
  top: 0;
  z-index: 1;
  white-space: nowrap;
}

.table tbody tr {
  transition: background-color 0.2s ease;
}

.table tbody tr:hover {
  background: var(--bg-hover, #f3f4f6);
}

.data-row {
  contain: layout style paint;
  will-change: background-color;
}

/* 表格内容样式 */
.log-action {
  font-weight: 500;
  color: var(--text, #111827);
}

.log-time {
  color: var(--text-secondary, #6b7280);
  font-size: var(--text-xs, 12px);
}

.log-user {
  color: var(--primary, #3b82f6);
  font-weight: 500;
}

.log-ip {
  font-family: 'Courier New', monospace;
  font-size: var(--text-xs, 12px);
  color: var(--text-secondary, #6b7280);
}

/* 筛选器样式 */
.filters {
  background: var(--card-bg, #ffffff);
  border-radius: var(--radius, 8px);
  box-shadow: var(--shadow, 0 2px 8px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--border-light, #e5e7eb);
  padding: var(--space-4, 16px);
  margin-bottom: var(--space-6, 24px);
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: var(--space-4, 16px);
  align-items: end;
}

.field {
  display: flex;
  flex-direction: column;
  gap: var(--space-2, 8px);
}

.field label {
  font-size: var(--text-sm, 14px);
  font-weight: 500;
  color: var(--text-secondary, #6b7280);
  margin-bottom: var(--space-1, 4px);
}

.input {
  padding: var(--space-2, 8px) var(--space-3, 12px);
  border: 1px solid var(--border, #d1d5db);
  border-radius: var(--radius-sm, 6px);
  font-size: var(--text-sm, 14px);
  background: var(--input-bg, #ffffff);
  color: var(--text, #111827);
  transition: all 0.2s ease;
}

.input:focus {
  outline: none;
  border-color: var(--primary, #3b82f6);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.input::placeholder {
  color: var(--text-muted, #9ca3af);
}

/* 动画效果 */
.slide-up {
  animation: slideUp 0.6s ease-out forwards;
  opacity: 0;
  transform: translateY(20px);
}

@keyframes slideUp {
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 性能优化相关样式 */
.table-wrapper {
  /* 启用硬件加速 */
  transform: translateZ(0);
  /* 优化滚动性能 */
  overflow-x: auto;
  -webkit-overflow-scrolling: touch;
}

.data-row {
  /* 优化行渲染性能 */
  contain: layout style;
  /* 减少重绘 */
  will-change: auto;
}

.data-row:hover {
  /* 使用transform而不是改变其他属性来提升性能 */
  transform: translateY(-1px);
  transition: transform 0.2s ease;
}

/* 虚拟化支持 */
.table tbody {
  /* 启用GPU加速 */
  transform: translate3d(0, 0, 0);
}

/* 加载状态优化 */
.loading-row {
  contain: layout style paint;
}

.spinner {
  /* 使用transform进行动画以获得更好的性能 */
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 分页控件优化 */
.pagination-controls {
  contain: layout;
}

.page-numbers button {
  /* 减少重排 */
  contain: layout style;
}

/* 模态框优化 */
.modal-overlay {
  /* 启用硬件加速 */
  transform: translateZ(0);
  backdrop-filter: blur(4px);
}

.modal {
  /* 优化模态框渲染 */
  contain: layout style paint;
  transform: translate3d(0, 0, 0);
}

/* 响应式优化 */
@media (max-width: 768px) {
  .table-wrapper {
    /* 移动端滚动优化 */
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
  }
  
  .data-row {
    /* 移动端减少动画以提升性能 */
    transition: none;
  }
}

/* 减少不必要的重绘 */
.badge {
  contain: layout style;
}

.btn {
  contain: layout;
}

/* 文本渲染优化 */
.error-message {
  /* 长文本优化 */
  word-break: break-word;
  contain: layout style;
}
</style>

<style scoped>
.error-message {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.log-detail {
  max-height: 400px;
  overflow-y: auto;
}

.detail-item {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid var(--border-light);
}

.detail-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.detail-item label {
  font-weight: 600;
  color: var(--text-secondary);
  display: block;
  margin-bottom: 5px;
}

.detail-value {
  background: var(--bg-light);
  padding: 8px 12px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  white-space: pre-wrap;
  word-break: break-all;
}

.badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.badge.success {
  background: var(--success-light);
  color: var(--success);
}

.badge.danger {
  background: var(--danger-light);
  color: var(--danger);
}

.badge.secondary {
  background: var(--bg-light);
  color: var(--text-secondary);
}
</style>
